#!/bin/bash
#此脚本用于生成ssh密钥对，并且可以达到跳板机框架如：s ip 即可跳入加入的任意一台机器,此脚本正常情况下在root家目录下执行，
#在root家目录下创建一个ip文件，里面放入ip和密码，格式如下：192.168.8.123:minerhub然后第二行，第三行等等,此脚本默认可以用root用户远程登录
user1=minerhub
user=root
catalog=/root/.ssh
[ ! -f $catalog ] &&  mkdir -p $catalog  && ssh-keygen -P '' -f $catalog/id_rsa
#判断是否安装expect
expect -version
#[ $? -ne 0 ] && yum install -y expect && echo "expect安装成功" #centos用
[ $? -ne 0 ] && apt -y install expect && echo "expect安装成功"  #ubuntu用
#判断IP是否都ping通并且推送公钥
for i in `cat ip`
do
	ip=`echo $i|cut -d: -f1`
	passwd=`echo  $i|cut -d: -f2`
	ping -c1 $ip &>/dev/null
	if [ $? -eq 0 ];then
	echo $ip >> ~/ip_up.txt
/usr/bin/expect <<-END
		set timeout 10
		spawn ssh-copy-id $user@$ip
	expect "yes/no"  {send "yes\r";exp_continue }
	expect "password:" { send  "$passwd\r" }
	spawn ssh $user@$ip
	expect "yes/no"  {send "yes\r";exp_continue }
        expect "password:" { send  "$passwd\r" }	
	expect ":~#" {send "chmod 600 /root/.ssh/authorized_keys\r"}
	expect ":~#" {send "sed -i '5aAuthorizedKeysFile  .ssh/authorized_keys .ssh/authorized_keys2' /etc/ssh/sshd_config\r"}
	expect ":~#" {send "sed -i '5aPubkeyAuthentication yes' /etc/ssh/sshd_config\r"}
	expect ":~#" {send "sed -i '5aPasswordAuthentication no' /etc/ssh/sshd_config\r"}	
	expect ":~#" {send "systemctl restart ssh\r"}
	expect eof	
END
	else
		echo $ip >>ip_down.txt
	fi
done
succeed=`cat ip_up.txt|wc -l`
echo "$succeed公钥推送成功"
error=`cat ip_down.txt|wc -l`
echo "$error个推送不成功，请查看ip_down.txt"
echo "alias s='ssh -l root -p 22 -o StrictHostKeyChecking=no'" >>/root/.bashrc
source /root/.bashrc
